<template>
  <div class="app-container">
    <el-card>
      <el-tabs v-model="queryParams.type" @tab-click="resetQuery">
        <el-tab-pane label="按产品汇总" name="1" />
        <el-tab-pane label="按分类汇总" name="2" />
      </el-tabs>
      <el-form ref="form" style="margin-top: 20px" :model="queryParams" inline>
        <el-form-item prop="type">
          <el-select
            v-model="queryParams.countType"
            placeholder="选择统计类型"
            @change="changeType"
          >
            <el-option
              v-for="(i, k) in dateTypeList"
              :key="k"
              :value="i.value"
              :label="i.label"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-date-picker
            v-model="time"
            :type="queryParams.countType"
            :value-format="dateFormat"
            :format="queryParams.countType == 'week' ? 'yyyy第WW周' : null"
            :firstDayOfWeek="1"
            placeholder="选择日期"
            @change="timeChange"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card style="margin-top: 20px">
      <div id="sales" />
    </el-card>
    <el-card style="margin-top: 20px">
      <div style="display: flex; justify-content: space-between">
        <div>销售数量：{{ saleTotal || 0 }}， 销售金额：¥ {{ priceTotal || 0 }}</div>
        <el-button type="primary" size="mini" @click="handleExcel">导出</el-button>
      </div>
      <el-table :data="dataList" border stripe style="margin-top: 20px">
        <el-table-column :label="`${queryParams.type == 1 ? '产品' : '分类'}名称`">
          <template slot-scope="scope">
            {{ getName(scope.row.type) }}
          </template>
        </el-table-column>
        <el-table-column prop="count" label="销售数量" />
        <el-table-column prop="amount" label="销售金额" />
      </el-table>
    </el-card>
  </div>
</template>

<script>
import * as echarts from "echarts";
import { getByproduct, getBytype } from "@/api/menu";
import { getTime } from "@/utils/common";
export default {
  name: "index",
  data() {
    return {
      queryParams: {
        type: "1",
        countType: "date",
        startTime: "",
        endTime: "",
      },
      dateFormat: "yyyy-MM-dd",
      time: "",
      dateTypeList: [
        { value: "date", label: "按日统计" },
        { value: "week", label: "按周统计" },
        { value: "month", label: "按月统计" },
        { value: "year", label: "按年统计" },
      ],
      dataList: [],
      saleTotal: 0, // 销售统计
      priceTotal: 0, // 销售金额统计
      // 类型列表
      typeList: [
        { value: "CLOUD_SERVER", label: "云服务器" },
        { value: "CLOUD_MARKET", label: "云市场" },
        { value: "GOV_CLOUD", label: "政务云" },
        { value: "CLOUD_SERVER_RENEW", label: "云服务器续费" },
        { value: "CLOUD_SERVER_CHANGE", label: "云服务器变更" },
        { value: "cpu", label: "CPU" },
        { value: "memory", label: "内存" },
        { value: "hardDisk", label: "硬盘" },
        { value: "defense", label: "防御" },
        { value: "bandwidth", label: "带宽" },
        { value: "ip", label: "IP" },
        { value: "other", label: "其它" },
      ],
    };
  },
  mounted() {
    this.getList();
  },
  wacth: {
    "queryParams.countType": {
      handler(type) {
        if (type == "week") {
          this.dateFormat = "yyyy-WW";
        } else if (type == "month") {
          this.dateFormat = "yyyy-MM";
        } else if (type == "year") {
          this.dateFormat = "yyyy";
        } else {
          this.dateFormat = "yyyy-MM-dd";
        }
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    // 查询
    handleQuery() {
      if (this.queryParams.startTime && this.queryParams.endTime) {
        this.getList();
      } else {
        this.$message.error(`请选择查询时间`);
      }
    },
    // 获取名称
    getName(val) {
      let row = this.typeList.find((item) => item.value == val);
      return row ? row.label : "";
    },
    // 重置
    resetQuery() {
      this.queryParams = {
        type: this.queryParams.type,
        countType: "date",
        startTime: "",
        endTime: "",
      };
      this.time = "";
      this.getList();
    },
    // 统计类型改变
    changeType(e) {
      this.time = "";
      this.queryParams.startTime = "";
      this.queryParams.endTime = "";
    },
    // 时间选择改变
    timeChange(e) {
      if (e == "" || e == null) {
        this.queryParams.startTime = "";
        this.queryParams.endTime = "";
        return;
      }
      let type = this.queryParams.countType;
      if (type == "date") {
        this.queryParams.startTime = e + " 00:00:00";
        this.queryParams.endTime = e + " 23:59:59";
      } else if (type == "week") {
        let date = new Date(e)
        //本周第一天
        let start = new Date(date.getTime() - (3600 * 1000 * 24 * (date.getDay() == 0 ? 6 : date.getDay())))
        //本周最后一天
        let end = new Date(date.getTime() + (3600*1000*24* (date.getDay()==0 ? 0:7- date.getDay()-1)))
        this.queryParams.startTime = getTime(start) + " 00:00:00";
        this.queryParams.endTime = getTime(end) + " 23:59:59";
      } else if (type == "month") {
        let date = new Date(e);
        let y = date.getFullYear();
        let m = date.getMonth();
        this.queryParams.startTime = getTime(new Date(y, m, 1)) + " 00:00:00";
        this.queryParams.endTime = getTime(new Date(y, m + 1, 0)) + " 23:59:59";
      } else if (type == "year") {
        let y = e.substr(0, 4);
        this.queryParams.startTime = y + "-01-01 00:00:00";
        this.queryParams.endTime = y + "-12-31 23:59:59";
      }
    },
    // 获取统计数据
    getList() {
      const { startTime, endTime } = this.queryParams;
      let axios = null;
      if (this.queryParams.type == 1) {
        getByproduct({ startTime, endTime }).then( res => {
          this.dataList = res.data;
          this.saleTotal = 0;
          this.priceTotal = 0;
          res.data.forEach((i) => {
            this.saleTotal += parseFloat(i.count);
            this.priceTotal += parseFloat(i.amount);
          });
          this.saleTotal = this.saleTotal.toFixed(0);
          this.priceTotal = this.priceTotal.toFixed(2);
          this.$nextTick(this.drawChart());
        });
      } else {
        getBytype({ startTime, endTime }).then( res => {
          this.dataList = res.data.list;
          this.saleTotal = res.data.total;
          this.priceTotal = res.data.salesVolume;
          this.$nextTick(this.drawChart());
        })
      }
    },
    // 图表
    drawChart() {
      let sales = document.getElementById("sales");
      if (sales.hasAttribute("_echarts_instance_"))
        sales.removeAttribute("_echarts_instance_");
      var myChart = echarts.init(sales);
      let option = {
        tooltip: {
          trigger: "axis",
          axisPointer: { type: "shadow" },
        },
        grid: {
          top: "3%",
          left: "0%",
          right: "0%",
          bottom: "0%",
          containLabel: true,
        },
        xAxis: [
          {
            type: "category",
            data: this.dataList.map((i) => {
              return this.typeList.find((t) => t.value == i.type).label;
            }),
            axisTick: { alignWithLabel: true },
          },
        ],
        yAxis: {
          splitLine: {
            show: true,
            lineStyle: { type: "dashed" },
          },
        },
        series: {
          name: `销量${this.queryParams.type == 1 ? "数量" : "金额"}`,
          type: "bar",
          barWidth: "30%",
          itemStyle: {
            normal: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: "#4098ff" },
                { offset: 0.5, color: "rgba(64, 152, 255, 0.5)" },
                { offset: 1, color: "rgba(64, 152, 255, 0.2)" },
              ]),
            },
          },
          data: this.dataList.map((i) =>
            this.queryParams.type == 1 ? i.count : i.amount
          ),
        },
      };
      myChart.setOption(option, true, true);
      window.addEventListener("resize", () => {
        myChart.resize();
      });
    },
    // 导出
    handleExcel() {
      const { startTime, endTime, type } = this.queryParams;
      if (type == 1) {
        this.download(
          "system/statistics/byProduct/export",
          { ...{ startTime, endTime } },
          `产品统计_${new Date().getTime()}.xlsx`
        );
      } else {
        this.download(
          "system/statistics/byType/export",
          { ...{ startTime, endTime } },
          `分类统计_${new Date().getTime()}.xlsx`
        );
      }
    },
  },
};
</script>
<style lang="scss" scoped>
#sales {
  width: 100%;
  height: 380px;
}
</style>
